package com.tangbuzhi.composite;

import java.util.ArrayList;
import java.util.List;

/**
 * 组合模式
 */
public class Composite {
    public static abstract class Component {
        protected String name;

        public Component(String name) {
            this.name = name;
        }

        public abstract void doSomething();
    }

    public static class Root extends Component {
        private List<Component> components = new ArrayList<>();

        public Root(String name) {
            super(name);
        }

        @Override
        public void doSomething() {
            System.out.println(name);
            if (components != null) {
                for (Component component : components) {
                    component.doSomething();
                }
            }
        }

        public void addChild(Component child) {
            components.add(child);
        }

        public void removeChild(Component child) {
            components.remove(child);
        }

        public Component getChild(int index) {
            return components.get(index);
        }
    }

    public static class Leaf extends Component {
        public Leaf(String name) {
            super(name);
        }

        @Override
        public void doSomething() {
            System.out.println(name);
        }
    }

    public static void main(String[] args) {
        Root root = new Root("root");

        Root branch1 = new Root("branch1");
        Root branch2 = new Root("branch2");
        Root branch3 = new Root("branch3");

        Leaf leaf1 = new Leaf("leaf1");
        Leaf leaf2 = new Leaf("leaf2");

        branch1.addChild(leaf1);
        branch1.addChild(leaf2);

        root.addChild(branch1);
        root.addChild(branch2);
        root.addChild(branch3);
        root.doSomething();
        /**
         root
         branch1
         leaf1
         leaf2
         branch2
         branch3
         */
    }
}
